package gormx

import (
	"fmt"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/migrator"
	"gorm.io/gorm/schema"
)

// 批量定义索引
func CreateIndexs(tx *gorm.DB, tableName string, idxs []schema.Index) error {
	f := func(idx schema.Index, m gorm.Migrator) error {
		if m.HasIndex(tableName, idx.Name) {
			return nil
		}

		opts := tx.Migrator().(migrator.BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, tx.Statement)
		values := []interface{}{clause.Column{Name: idx.Name}, clause.Table{Name: tableName}, opts}
		createIndexSQL := "CREATE "
		if idx.Class != "" {
			createIndexSQL += idx.Class + " "
		}
		createIndexSQL += "INDEX ? ON ??"

		if idx.Type != "" {
			createIndexSQL += " USING " + idx.Type
		}

		if idx.Comment != "" {
			createIndexSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment)
		}

		if idx.Option != "" {
			createIndexSQL += " " + idx.Option
		}

		return tx.Exec(createIndexSQL, values...).Error
	}

	for _, idx := range idxs {
		if err := f(idx, tx.Migrator()); err != nil {
			return err
		}
	}

	return nil
}

// 批量修改列
func AlterColumnsWithMySQL(db *gorm.DB, tableName string, fields []*schema.Field) error {
	for _, field := range fields {
		fileType := db.Dialector.DataTypeOf(field)
		if err := db.Exec(
			"ALTER TABLE ? MODIFY COLUMN ?  ?",
			clause.Table{Name: tableName}, clause.Column{Name: field.DBName}, clause.Expr{SQL: fileType},
		).Error; err != nil {
			return err
		}
	}

	return nil
}
